package priv.pront.code.national.acwing.graph;

import java.util.*;

public class A847_图中点的层次 {

    static int n, idx, m;
    static int[] h, e, ne, d;
    static Queue<Integer> queue = new LinkedList<>();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();
        h = new int[n + 1];
        e = new int[m + 1];
        ne = new int[m + 1];
        d = new int[n + 1];
        Arrays.fill(h, -1);
        Arrays.fill(d, -1);
        for (int i = 0; i < m; i++) add(scanner.nextInt(), scanner.nextInt());
        System.out.println(bfs(1));
    }

    private static int bfs(int u) {
        d[1] = 0;
        queue.offer(u);
        while (!queue.isEmpty()) {
            int t = queue.poll();
            for (int i = h[t]; i != -1; i = ne[i]) {
                int j = e[i];
                if (d[j] == -1) {
                    queue.offer(j);
                    d[j] = d[t] + 1;
                }
            }
        }
        return d[n];
    }

    private static void add(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }
}
